package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RocketMQMessageListener(consumerGroup ="MQSeckillOrderListener" ,topic =MQConstant.ORDER_PEDDING_TOPIC)
public class MQSeckillOrderListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("已经进入下单的队列中了");
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long userPhone = orderMessage.getUserPhone();
        String tag="";

        OrderMQResult orderMQResult=new OrderMQResult();
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setTime(time);
        orderMQResult.setToken(token);
        try {
            //int i=1/0;
            //执行秒杀流程返回订单编号
            tag=MQConstant.ORDER_RESULT_SUCCESS_TAG;
            String orderNo = orderInfoService.doseckill(time, seckillId, userPhone);
            orderMQResult.setOrderNo(orderNo);
            //延迟消息发送 Order time seckillId orderNO token
            MessageBuilder<OrderMQResult> messageBuilder=MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,messageBuilder.build(),5000,5);
        }catch (Exception e){
            tag=MQConstant.ORDER_RESULT_FAIL_TAG;
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
        }
        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);
    }
}
